#include "../include/main.h"


//开关linux下的终端回显，
//函数set_disp_mode用于控制是否开启输入回显功能  
//如果option为0，则关闭回显，为1则打开回显  
#include <termios.h>  
#include <unistd.h>  
#include <errno.h>
#define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL)  

int set_disp_mode(int fd,int option)  
{  
   int err;  
   struct termios term;  
   if(tcgetattr(fd,&term)==-1){  
     perror("Cannot get the attribution of the terminal");  
     return 1;  
   }  
   if(option)  
        term.c_lflag|=ECHOFLAGS;  
   else  
        term.c_lflag &=~ECHOFLAGS;  
   err=tcsetattr(fd,TCSAFLUSH,&term);  
   if(err==-1 && err==EINTR){  
        perror("Cannot set the attribution of the terminal");  
        return 1;  
   }  
   return 0;  
}


//轮询判断是否有键盘写入
int kbhit(void)
{
    #ifdef WIN_SYS
    return _kbhit();
    #else 
    fd_set rfds;
    struct timeval tv;
    int retval;

    /* Watch stdin (fd 0) to see when it has input. */
    FD_ZERO(&rfds);
    FD_SET(0, &rfds);
    /* Wait up to five seconds. */
    tv.tv_sec  = 0;
    tv.tv_usec = 0;

    retval = select(1, &rfds, NULL, NULL, &tv);
    /* Don't rely on the value of tv now! */

    if (retval == -1) {
            perror("select()");
            return 0;
    } else if (retval)
            return 1;
    /* FD_ISSET(0, &rfds) will be true. */
    else
            return 0;
    return 0;

    #endif
}

//兼容win和linux的sleep函数
void common_sleep(int ms){
    #ifdef WIN_SYS
    Sleep(ms);
    #else
    usleep(ms * 1000);
    #endif
}